package com.jmpt.fangbohui.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.adapter.BrokerAgentFilterRightAdapter;
import com.jmpt.fangbohui.adapter.BrokerListAdpter;
import com.jmpt.fangbohui.adapter.HouseSelectProportionAdapter;
import com.jmpt.fangbohui.adapter.HouseSeleteMoreAdapter;
import com.jmpt.fangbohui.adapter.HouseSeleteMoreRightAdapter;
import com.jmpt.fangbohui.adapter.NewHouseSelectPriceAdapter;
import com.jmpt.fangbohui.adapter.NewHouseSelectRegionAdapter;
import com.jmpt.fangbohui.bean.BrokerCompanyBean;
import com.jmpt.fangbohui.bean.BrokersListBean;
import com.jmpt.fangbohui.bean.HouseMoreCategoryItemValuesBean;
import com.jmpt.fangbohui.bean.HouseMoreSeleteCategoryBean;
import com.jmpt.fangbohui.bean.NewHouseBean;
import com.jmpt.fangbohui.helper.CommonHelper;
import com.jmpt.fangbohui.http.ApiRequest;
import com.jmpt.fangbohui.http.ApiUrl;
import com.jmpt.fangbohui.http.JsonHttpHandler;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ImageLoaderHelper;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.jmpt.fangbohui.utils.UIUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

public class BrokersListActivity extends BaseHeadActivity {
	
	protected static final int SEARCH_REQUEST_CODE = 2121;

	@ViewInject(R.id.plv_broker_list_content)
	private PullToRefreshListView mPlv;
	
	@ViewInject(R.id.btn_brokers_list_company)
	private Button mBtnCompanySelete;
	
	@ViewInject(R.id.btn_brokers_list_locationSelete)
	private Button btn_locationSelete;
	
	@ViewInject(R.id.vs_broker_list_seleteArea)
	private ViewStub mVsseleteArea;
	
	private View v_seleteArea;
	
	private BrokerListAdpter mAdpter;
	
	private boolean isNoMore;

	private boolean isFirstLoad;

	//一页显示10条数据
	private int limit = 10;
	
//	private String searchKey;

	private int mCurrenRegionIndex;

	private ImageView iv_seleteArea;

	private ListView lv_seleteArea_left;

	private ListView lv_seleteArea_right;
	
	private NewHouseSelectRegionAdapter mSeleteRegionAdapter;
	private BrokerAgentFilterRightAdapter mAgentFilterLeftAdapter;
	private HouseSeleteMoreRightAdapter mSeleteMoreRightAdapter;
	
	private String currSearchKey;

	private int mCurrenCompanyIndex = -1;

	private int mCurrenLocationIndex = -1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// 设置标题
		showTitle("经纪人");
		// 设置返回键
		showBackButton(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		showRightImageButton(R.drawable.ic_home_search,
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						 Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
						 intent.putExtra(SearchActivity.CURR_KEY, currSearchKey);
						 intent.putExtra(SearchActivity.SEARCH_HINT, "经纪人姓名/手机号码搜索");
						 startActivityForResult(intent,SEARCH_REQUEST_CODE);
					}
				});

		setContentView(R.layout.activity_brokers_list);
		
		ViewUtils.inject(this);
		
		// 查找筛选区域视图
		v_seleteArea = mVsseleteArea.inflate();
		v_seleteArea.setVisibility(View.INVISIBLE);
		assignSeleteViews(v_seleteArea);
		
		initView();
		
		initData();
		
		initSeleteView();
		
		refreshCompanyButtonName();
		
		fistLoad();
		
	}
	
	private void assignSeleteViews(View view) {
		iv_seleteArea = (ImageView) view
				.findViewById(R.id.iv_house_group_select_background);
		lv_seleteArea_left = (ListView) view
				.findViewById(R.id.lv_house_group_select_left);
		lv_seleteArea_right = (ListView) view
				.findViewById(R.id.lv_house_group_select_right);
	}

	private void initView() {
		mAdpter = new BrokerListAdpter(this);
		mPlv.setAdapter(mAdpter);
		mPlv.setMode(PullToRefreshBase.Mode.BOTH);
		mPlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> adapterView,
							View view, int i, long l) {
					     try {
							//网店详情
							 Intent intent = new Intent(BrokersListActivity.this, BrokerShopActivity.class);
							 intent.putExtra(BrokerShopActivity.UID_EXTRA_KEY, mAdpter.data.get(i - 1).getUid());
							 intent.putExtra(BrokerShopActivity.PHONE_EXTRA_KEY, mAdpter.data.get(i - 1).getPhone());
							 intent.putExtra(BrokerShopActivity.PICURL_EXTRA_KEY, mAdpter.data.get(i - 1).getPicUrl());
							 intent.putExtra(BrokerShopActivity.USERNAME_EXTRA_KEY, mAdpter.data.get(i - 1).getUsername());
							 intent.putExtra(BrokerShopActivity.ZJCNAME_EXTRA_KEY, mAdpter.data.get(i - 1).getZjcname());
							 startActivity(intent);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
		
		mPlv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						fistLoad();
					}
					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						if(isNoMore){
							ToastHelper.ShowToast("没有更多数据了", getApplicationContext());
							mPlv.onRefreshComplete();
							return;
						}
						// 加载更多
						loadMore();
					}
				});

		mPlv.setOnScrollListener(new PauseOnScrollListener(ImageLoaderHelper.getImageLoader(), true, true));  
		
	}

	private void initData() {
		
		mSeleteRegionAdapter = new NewHouseSelectRegionAdapter(this);
		mSeleteRegionAdapter.data = CommonHelper.getAgentRegionBeans();
		
		mAgentFilterLeftAdapter = new BrokerAgentFilterRightAdapter(this);
		mAgentFilterLeftAdapter.data = CommonHelper.getBrokerAgentListBeans();
		
		//公司筛选 适配器
		mSeleteMoreRightAdapter = new HouseSeleteMoreRightAdapter(this, null);
		
	}
	
	public void initSeleteView() {
		lv_seleteArea_left
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						
						if (lv_seleteArea_left.getAdapter() instanceof NewHouseSelectRegionAdapter) {

							mCurrenLocationIndex = position;
							
							for (int i = 0; i < mSeleteRegionAdapter.data
									.size(); i++) {
								mSeleteRegionAdapter.data.get(i).isSelete = false;
							}
							mSeleteRegionAdapter.data.get(position).isSelete = true;
							mSeleteRegionAdapter.notifyDataSetChanged();
							hideSeleteArea();
							fistLoad();
							refreshLocationButtonName();
						}
						
						if(lv_seleteArea_left.getAdapter() instanceof BrokerAgentFilterRightAdapter){
							mCurrenRegionIndex= position; 
							
							if(position == 0){ //不限
								
								mCurrenCompanyIndex = -1;
								//清空所有区域子公司选择下标
								for (int i = 0; i < mAgentFilterLeftAdapter.data.size(); i++) {
									mAgentFilterLeftAdapter.data.get(i).childSelete = -1;
									mAgentFilterLeftAdapter.data.get(i).isSelete = false;
								}
								
//								mAgentFilterLeftAdapter.data.get(0).isSelete = true;
//								mAgentFilterLeftAdapter.data.get(0).childSelete = mCurrenCompanyIndex;
								
								mAgentFilterLeftAdapter.notifyDataSetChanged();
								
								refreshCompanyButtonName();
								hideSeleteArea();
								fistLoad();
								
							}else if (mAgentFilterLeftAdapter.data.get(position).values == null) { //没有改区域的数据
								refreshAgentRegionSelect(position);
								//访问服务器
								loadCompany(position);
								
							}else if(mAgentFilterLeftAdapter.data.get(position).values.size() == 0){ //改区域公司为0
								refreshAgentRegionSelect(position);
								mSeleteMoreRightAdapter.data = mAgentFilterLeftAdapter.data.get(position);
								mSeleteMoreRightAdapter.notifyDataSetChanged();
//								hideSeleteArea(); 
//								fistLoad();
								ToastHelper.ShowToast("该地区暂无中介公司", UIUtils.getContext());
							}else { //有该区域公司列表
								refreshAgentRegionSelect(position);
								mSeleteMoreRightAdapter.data = mAgentFilterLeftAdapter.data.get(position);
								mSeleteMoreRightAdapter.notifyDataSetChanged();
							}
						}
					}
				});

		lv_seleteArea_right
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						
						mCurrenCompanyIndex = position;
						
						for (int i = 0; i < mAgentFilterLeftAdapter.data.size(); i++) {
							if (mAgentFilterLeftAdapter.data.get(i) == mSeleteMoreRightAdapter.data) {
								mCurrenRegionIndex = i;
								mAgentFilterLeftAdapter.data.get(i).isSelete = true;
							} else {
								mAgentFilterLeftAdapter.data.get(i).isSelete = false;
							}
							
							mAgentFilterLeftAdapter.data.get(i).childSelete = -1;
						}
						
						mSeleteMoreRightAdapter.data.childSelete = position;
						
						mAgentFilterLeftAdapter.notifyDataSetChanged();
						
						refreshCompanyButtonName();
						hideSeleteArea();
						fistLoad();
					}
				});
		
		iv_seleteArea.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				hideSeleteArea();
			}
		});
		
	}
	
	protected void refreshLocationButtonName() {
		if(mCurrenLocationIndex == 0){
			btn_locationSelete.setText("区域");
		}else{
			btn_locationSelete.setText(mSeleteRegionAdapter.data
					.get(mCurrenLocationIndex).ZoneName);
		}
		
	}

	/**
	 * 刷新区域选择
	 * @param position
	 */
	private void refreshAgentRegionSelect(int position) {
		for (int i = 0; i < mAgentFilterLeftAdapter.data.size(); i++) {
			mAgentFilterLeftAdapter.data.get(i).isSelete = false;
		}
		mAgentFilterLeftAdapter.data.get(position).isSelete = true;
		mAgentFilterLeftAdapter.notifyDataSetChanged();
	}
	
	/**
	 * 获取区域公司
	 * @param id
	 */
	protected void loadCompany(final int position) {
		String regionId = mAgentFilterLeftAdapter.data.get(position).id;
		//
		ApiRequest.getBrokerCompanyList(regionId,new JsonHttpHandler(this){
			
			@Override
			public void onStart() {
				setShowProgressDialog("加载中...");
				super.onStart();
			}
			@Override
			public void onDo(String response) {
				Gson g = new Gson();
				List<BrokerCompanyBean> list =g.fromJson(response.toString(), new TypeToken<List<BrokerCompanyBean>>() {}.getType());
				appendCompanyList(list, position);
			}
		});
		
	}

	protected void appendCompanyList(List<BrokerCompanyBean> list, int position) {
		
		List<HouseMoreCategoryItemValuesBean> values = new ArrayList<HouseMoreCategoryItemValuesBean>();
		
		HouseMoreCategoryItemValuesBean rightItemBean;
//		rightItemBean.name = "不限";
//		values.add(rightItemBean);
		
//		if(list == null){
//			mSeleteRegionAdapter.data.get(position).values = values;
//			refreshRegionSelect(position);
//            hideSeleteArea();
//            fistLoad();
//			return ;
//		}
		
		if(list != null){
			for (BrokerCompanyBean companyBean : list) {
				rightItemBean = new HouseMoreCategoryItemValuesBean();
				rightItemBean.name = companyBean.zjcname;
				rightItemBean.urlValue = companyBean.zjid;
				values.add(rightItemBean);
			}
		}
		
		mAgentFilterLeftAdapter.data.get(position).values = values;
		mSeleteMoreRightAdapter.data = mAgentFilterLeftAdapter.data.get(position);
		
    	mAgentFilterLeftAdapter.notifyDataSetChanged();
    	mSeleteMoreRightAdapter.notifyDataSetChanged();
		
    	if(values.size() == 0){
    		ToastHelper.ShowToast("该地区暂无中介公司", UIUtils.getContext());
    	}
    	
	}

	@OnClick(R.id.btn_brokers_list_company)
	public void seleteCompany(View view){
		if (v_seleteArea.getVisibility() == View.VISIBLE) {
			if(lv_seleteArea_left.getAdapter() instanceof BrokerAgentFilterRightAdapter){
				
				hideSeleteArea();
			}else{
				lv_seleteArea_left.setAdapter(mAgentFilterLeftAdapter);
				mAgentFilterLeftAdapter.notifyDataSetChanged();
				lv_seleteArea_right.setVisibility(View.VISIBLE);
				lv_seleteArea_right.setAdapter(mSeleteMoreRightAdapter);
				mSeleteMoreRightAdapter.data = mAgentFilterLeftAdapter.data.get(mCurrenRegionIndex);
				mSeleteMoreRightAdapter.notifyDataSetChanged();
			}
		} else {
			lv_seleteArea_left.setAdapter(mAgentFilterLeftAdapter);
			mAgentFilterLeftAdapter.notifyDataSetChanged();
			lv_seleteArea_right.setVisibility(View.VISIBLE);
			lv_seleteArea_right.setAdapter(mSeleteMoreRightAdapter);
			mSeleteMoreRightAdapter.data = mAgentFilterLeftAdapter.data.get(mCurrenRegionIndex);
			mSeleteMoreRightAdapter.notifyDataSetChanged();
			showSeleteArea();
		}
		
	}
	@OnClick(R.id.btn_brokers_list_locationSelete)
	public void seleteLocation(View view){
		if (v_seleteArea.getVisibility() == View.VISIBLE) {
			if (lv_seleteArea_left.getAdapter() instanceof NewHouseSelectRegionAdapter) {
				hideSeleteArea();
			} else {                 
				lv_seleteArea_left.setAdapter(mSeleteRegionAdapter);
				mSeleteRegionAdapter.notifyDataSetChanged();
				lv_seleteArea_right.setVisibility(View.GONE);
			}
		} else {
			lv_seleteArea_left.setAdapter(mSeleteRegionAdapter);
			mSeleteRegionAdapter.notifyDataSetChanged();
			lv_seleteArea_right.setVisibility(View.GONE);
			showSeleteArea();
		}
		
	}
	
	protected void refreshCompanyButtonName() {
		if(mCurrenRegionIndex == 0){
			mBtnCompanySelete.setText("中介公司");
		}else{
			HouseMoreSeleteCategoryBean region = mAgentFilterLeftAdapter.data.get(mCurrenRegionIndex);
		    mBtnCompanySelete.setText(region.values.get(mCurrenCompanyIndex).name);
		}
	}
	
	private void fistLoad() {
		isNoMore = false;
		load(true);
	}
	
	private void loadMore() {
		load(false);
	}
	
	private void load(boolean isFrist) {
		isFirstLoad = isFrist;
//		
//		String orderType = "";
		String zoneId = "";
		String companyId = "";
//		if (mCurrenOrderIndex > 0) {
//			orderType = mSelectOrderAdapter.data.get(mCurrenOrderIndex).type;
//		}
		
		if (mCurrenLocationIndex > 0) {
			zoneId = String.valueOf(mSeleteRegionAdapter.data
					.get(mCurrenLocationIndex).ZoneID);
		}
		
		if(mAgentFilterLeftAdapter.data != null){
			for (HouseMoreSeleteCategoryBean more : mAgentFilterLeftAdapter.data) {
				if (more.childSelete >= 0 && more.values != null && more.values.size() > 0 ) {
					companyId = more.values.get(more.childSelete).urlValue;
					break;
				}
			}
		}
		
		DebugLog.e("zoneId : " + zoneId + " companyId : " + companyId);
		
		int page;
		//是否是第一次加载 | 或者更改筛选条件后重新加载
		if (isFirstLoad) {
			page = 1;
		} else {
			//追加数据
			page = mAdpter.getCount() / limit  + 1;
		}
		
		addRequestHandle(ApiRequest.getBrokerListData(this, zoneId, companyId ,currSearchKey, page, new BrokerListJsonHolder(this)));
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == SEARCH_REQUEST_CODE && resultCode == RESULT_OK && data != null){
			String stringExtra = data.getStringExtra("search_key");
			currSearchKey = stringExtra;
			
			if(!TextUtils.isEmpty(currSearchKey)){
				showTitle("搜索 \"" + currSearchKey + "\"");
			}else{
				showTitle("经纪人");
			}
			
			fistLoad();
			
			return;
		}
	}

	public class BrokerListJsonHolder extends JsonHttpHandler{

		public BrokerListJsonHolder(Context context) {
			super(context);
		}
		
		@Override
		public void onStart() {
			if (isFirstLoad) {
				setShowProgressDialog("正在加载中...");
			} else {
				//增加加载更多
				mPlv.setRefreshing(true);
			}
			super.onStart();
		}
		
		@Override
		public void onDo(String response) {
			BrokersListBean entities = new Gson().fromJson(response.toString(),BrokersListBean.class);
			
			if (isFirstLoad) {
				mAdpter.data.clear();
			}
			mPlv.onRefreshComplete();
			if(entities != null && entities.getDate_row_house() != null){
				if (entities.getDate_row_house().size() >= limit) {
					mPlv.setMode(PullToRefreshBase.Mode.BOTH);
				}else{
					mPlv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
					//只能刷新 ， 不可加载更多
					isNoMore = true; //无更多数据了
				}
				mAdpter.data.addAll(entities.getDate_row_house());
			}else{
				mPlv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
				//只能刷新 ， 不可加载更多
				isNoMore = true; //无更多数据了
			}
			
			mAdpter.notifyDataSetChanged();
			
			if(isFirstLoad){
				mPlv.getRefreshableView().setSelection(0);
				showSubTitle("找到经纪人 " + entities.getTotalNumber() + " 位");
			}
		}
		
		@Override
		public void onFinish() {
			super.onFinish();
			mPlv.onRefreshComplete();
		}
	}
	
	

	/**
	 * 隐藏条件筛选区
	 */
	private void hideSeleteArea() {
		ObjectAnimator animator = ObjectAnimator.ofFloat(lv_seleteArea_left,
				"translationY", 0, -lv_seleteArea_left.getHeight());
		animator.addListener(new Animator.AnimatorListener() {
			@Override
			public void onAnimationStart(Animator animation) {

			}

			@Override
			public void onAnimationEnd(Animator animation) {
				v_seleteArea.setVisibility(View.INVISIBLE);
			}

			@Override
			public void onAnimationCancel(Animator animation) {

			}

			@Override
			public void onAnimationRepeat(Animator animation) {

			}
		});

		ObjectAnimator translationRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "translationY", 0,-lv_seleteArea_right.getHeight());
		ObjectAnimator alphaArea = ObjectAnimator.ofFloat(iv_seleteArea, "alpha", 1f, 0f);
		ObjectAnimator alphaRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "alpha", 1f, 0f);
		AnimatorSet set = new AnimatorSet();
		set.playTogether(animator,translationRight,alphaArea,alphaRight);
		set.start();
	}
	
	 private void showSeleteArea() {

	        ViewTreeObserver vto2 = lv_seleteArea_left.getViewTreeObserver();

	        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
	            @Override
	            public void onGlobalLayout() {
	            	lv_seleteArea_left.getViewTreeObserver().removeGlobalOnLayoutListener(this);
	                int height = lv_seleteArea_left.getHeight();
	                int width = lv_seleteArea_left.getWidth();
	                DebugLog.e("height: " + height);
	                DebugLog.e("width: " + width);
	                if (lv_seleteArea_left.getAdapter() instanceof BrokerAgentFilterRightAdapter) {
//	                    ViewGroup.LayoutParams layoutParams = lv_seleteArea_right.getLayoutParams();
//	                    layoutParams.height = height;
//	                    lv_seleteArea_right.setLayoutParams(layoutParams);
	                    lv_seleteArea_right.setVisibility(View.VISIBLE);
	                } else {
	                	lv_seleteArea_right.setVisibility(View.GONE);
	                }
	                
	                ObjectAnimator animatorLeft = ObjectAnimator.ofFloat(lv_seleteArea_left, "translationY", -lv_seleteArea_left.getHeight(), 0);

	                animatorLeft.addListener(new Animator.AnimatorListener() {
	                    @Override
	                    public void onAnimationStart(Animator animation) {

	                        v_seleteArea.setVisibility(View.VISIBLE);

	                    }

	                    @Override
	                    public void onAnimationEnd(Animator animation) {

	                    }

	                    @Override
	                    public void onAnimationCancel(Animator animation) {

	                    }

	                    @Override
	                    public void onAnimationRepeat(Animator animation) {

	                    }
	                });
	                ObjectAnimator alphaArea = ObjectAnimator.ofFloat(iv_seleteArea, "alpha", 0f, 1f);
	                ObjectAnimator translationRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "translationY", -lv_seleteArea_right.getHeight(), 0);
	                ObjectAnimator alphaRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "alpha", 0f, 1f);
	                AnimatorSet set = new AnimatorSet();
	                set.playTogether(animatorLeft,translationRight,alphaArea,alphaRight);
	                set.start();
	            }
	        });
	    }
}
